﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace WJP.ComponentModel
{
    /// <summary>
    /// 插件源基类
    /// </summary>
    public abstract class PluginSourceBase : IPluginSource
    {
        List<Assembly> _pluginInfos;

        public List<Assembly> GetAssemblies()
        {
            if (_pluginInfos == null)
                _pluginInfos = LoadAssemblies();
            return _pluginInfos;
        }

        /// <summary>
        /// 获取所有插件
        /// </summary>
        /// <returns></returns>
        public virtual List<Type> GetPlugins()
        {
            var plugins = new List<Type>();

            foreach (var assembly in GetAssemblies())
            {
                try
                {
                    foreach (var type in assembly.GetTypes())
                    {
                        if (PluginBase.IsPlugin(type))
                        {
                            plugins.AddIfNotContaines(type);
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception("无法从程序集：{0}获取插件".FormatArgs(assembly.FullName, ex));
                }
            }

            return plugins;
        }

        protected abstract List<Assembly> LoadAssemblies();
    }
}
